<template>
  <el-form label-width="100px" :model="form" :rules="rules" ref="ruleFormRef">
    <el-card class="card-item">
      <template #header>
        <div class="card-header">商品类别</div>
      </template>
      <el-form-item label="商品类别" prop="category">
        <el-select
          v-model="form.category"
          value-key="spuCategoryId"
          @change="onCategoryCodeChange"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.spuCategoryId"
            :label="item.categoryName"
            :value="item"
          />
        </el-select>
      </el-form-item>
    </el-card>

    <el-card class="card-item">
      <template #header>
        <div class="card-header">商品基本信息</div>
      </template>
      <el-form-item label="商品主图" prop="spuPhoto">
        <Upload
          :originFileList="form.spuPhoto"
          :limit="1"
          :onChange="(value: any) => form.spuPhoto = value"
        />
      </el-form-item>
      <el-form-item label="商品轮播图" prop="spuAlbum">
        <Upload
          :originFileList="form.spuAlbum"
          :limit="5"
          :onChange="(value: any) => form.spuAlbum = value"
        />
      </el-form-item>
      <el-form-item label="">
        最多可以上传 5 张图片，建议尺寸 800*800px
      </el-form-item>
      <el-form-item label="商品名称" prop="spuName">
        <el-input v-model="form.spuName" />
      </el-form-item>
      <el-form-item label="商品单位" prop="spuUnit">
        <el-input v-model="form.spuUnit" />
      </el-form-item>
      <el-form-item label="商品品牌" prop="spuBrand">
        <el-input v-model="form.spuBrand" />
      </el-form-item>
      <el-form-item label="商品描述" prop="spuDescription">
        <Editor
          :value="form.spuDescription"
          :onBlur="(value: string) => form.spuDescription = value"
        ></Editor>
      </el-form-item>
    </el-card>
    <el-card class="card-item" v-if="!hasSku">
      <template #header>
        <div class="card-header">库存规格</div>
      </template>
      <el-form-item label="商品编号" prop="skuCode">
        <el-input v-model="form.skuCode" />
      </el-form-item>
      <el-form-item label="商品售价" prop="skuPrice">
        <el-input-number v-model="form.skuPrice" :precision="2" :min="0.01" />
      </el-form-item>
      <el-form-item label="商品库存" prop="skuStock">
        <el-input-number v-model="form.skuStock" :precision="0" :min="0" />
      </el-form-item>
    </el-card>
    <el-card class="card-item" v-if="hasSku">
      <template #header>
        <div class="card-header">商品属性（服装规格）</div>
      </template>
      <div>
        <el-form-item>
          <SelectProductAttrs
            :spuCategoryAttrList="spuCategoryAttrList"
            :submit="updateTableData"
          />
        </el-form-item>
        <el-form-item prop="tableData">
          <el-table border :data="form.tableData" style="width: 800px">
            <el-table-column
              v-for="itemAttr in spuCategoryAttrList"
              :prop="`attr${itemAttr.spuCategoryAttrId}`"
              :label="itemAttr.attrName"
            />
            <el-table-column prop="stock" label="库存" width="180">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.stock"
                  :precision="0"
                  :min="0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品编码" width="200">
              <template #default="scope">
                <el-input v-model="scope.row.code" />
              </template>
            </el-table-column>
            <el-table-column prop="code" label="商品售价" width="200">
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.price"
                  :precision="2"
                  :min="0.01"
                />
              </template>
            </el-table-column>
            <!--  -->
          </el-table>
        </el-form-item>
      </div>
    </el-card>
    <el-card class="card-item">
      <template #header>
        <div class="card-header">商品详情图</div>
      </template>
      <el-form-item label="" prop="spuDescAlbum">
        <Upload
          :originFileList="form.spuDescAlbum"
          :limit="5"
          :onChange="(value: any) => form.spuDescAlbum = value"
        />
      </el-form-item>
      <el-form-item label="">
        最多可以上传 5 张图片，建议尺寸 800*800px
      </el-form-item>
    </el-card>
    <el-card class="card-item">
      <template #header>
        <div class="card-header">商品类别</div>
      </template>
      <el-form-item label="支付方式" prop="paymentModeList">
        <el-checkbox-group v-model="form.paymentModeList">
          <el-checkbox label="微信支付" value="wx" />
          <el-checkbox label="积分支付" value="points" />
        </el-checkbox-group>
      </el-form-item>
    </el-card>
    <el-form-item>
      <el-button
        type="primary"
        @click="submitForm(ruleFormRef)"
        :loading="submitLoading"
      >
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import {
  getProductCategory,
  addProduct,
  getProductDetail,
  updateProduct,
  getProductCategoryDetail,
} from "@/api/shop/index";
import { CategoryOption } from "./type";
import { transformToEdit, transformToSubmit } from "./utils";
import Upload from "../components/Upload.vue";
import SelectProductAttrs from "../components/select-product-attrs.vue";
import Editor from "@/components/Editor/index.vue";
import router from "@/router";
import { useRoute } from "vue-router";
const route = useRoute();

const submitLoading = ref(false);

const ruleFormRef = ref<FormInstance>();
// 商品信息表单
const form = reactive<any>({
  category: "",
  // 商品基本信息
  spuPhoto: [],
  spuName: "",
  spuBrand: "",
  spuDescription: "",
  skuCode: "",
  skuPrice: 1.0,
  skuStock: 1,
  // 商品属性
  tableData: [],
  // 商品相册
  spuAlbum: [],
  // 支付方式
  paymentModeList: ["wx", "points"]
});

const rules = reactive<any>({
  category: [{ required: true, message: "请选择商品类别" }],
  spuPhoto: [{ required: true, message: "请上传商品图片" }],
  spuAlbum: [{ required: true, message: "请上传商品轮播图" }],
  spuName: [{ required: true, message: "请输入商品名称" }],
  spuUnit: [{ required: true, message: "请输入商品单位" }],
  spuBrand: [{ required: true, message: "请输入商品品牌" }],
  spuDescription: [{ required: true, message: "请输入商品介绍" }],
  skuCode: [{ required: true, message: "请输入商品编号" }],
  skuPrice: [{ required: true, message: "请输入商品售价" }],
  skuStock: [{ required: true, message: "请输入商品库存" }],
  spuDescAlbum: [{ required: true, message: "请上传商品详情图" }],
  sizeCheckList: [{ required: true, message: "请选择尺码" }],
  colorCheckList: [{ required: true, message: "请选择颜色" }],
  tableData: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (
          !value || !value.length ||
          value.some(
            (item: any) => !item.code || (!item.stock && item.stock !== 0)
          )
        ) {
          callback(new Error("请将商品库存和编码信息补充完整"));
        }
        callback();
      },
    },
  ],
  paymentModeList: [{ required: true, message: "请选择支付方式" }],
});

// 商品类别
const categoryOptions = ref<CategoryOption[]>([]);

// 商品属性（商品规格相关）
const spuCategoryAttrList = ref<any[]>([]);
const hasSku = computed(() => {
  return spuCategoryAttrList.value && spuCategoryAttrList.value.length > 0;
});

const onCategoryCodeChange = (value: any) => {
  fetchProductCategoryDetail(value);
};

// 获取商品类别详情
const fetchProductCategoryDetail = (value: any) => {
  getProductCategoryDetail({
    spuCategoryId: value.spuCategoryId,
  })
    .then((res) => {
      spuCategoryAttrList.value = res.data.spuCategoryAttrList || [];
    })
    .catch((err) => {
      console.error(err);
    });
};

// 获取商品类别
const getProductCategoryList = () => {
  getProductCategory().then((res) => {
    categoryOptions.value = res.data || [];
  });
};

// 查询商品详情
const fetchProductDetail = (spuId: string) => {
  getProductDetail({
    spuId,
  }).then(async (res) => {
    // 根据 categoryCode 匹配当前商品类别
    const category = categoryOptions.value.filter(
      (i) => i.categoryCode === res.data.categoryCode
    )[0];
    // 获取商品类别详情
    const { data } = await getProductCategoryDetail({
      spuCategoryId: category?.spuCategoryId,
    });
    spuCategoryAttrList.value = data.spuCategoryAttrList;
    // 编辑数据回显
    const formData = transformToEdit(
      {
        ...res.data,
        category: category,
      },
      data.spuCategoryAttrList
    );
    console.log("----", formData);

    Object.assign(form, formData);
  });
};

// 页面初始化
const init = () => {
  getProductCategoryList();
  const spuId = route.query.spuId;
  if (spuId) {
    fetchProductDetail(spuId as string);
  }
};
init();

const updateTableData = ({ tableData, formData }: any) => {
  form.tableData = tableData;
  Object.keys(formData).forEach((key) => {
    form[key] = formData[key];
  });
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      submitLoading.value = true;
      try {
        const data = transformToSubmit(form, spuCategoryAttrList.value);
        console.log("🚀 ~ awaitformEl.validate ~ data:", data);

        if (route.query.spuId) {
          updateProduct({
            spuId: route.query.spuId,
            ...data,
          }).then(() => {
            ElMessage.success("更新成功");
            submitLoading.value = false;
            setTimeout(() => {
              router.push("/shop/product");
            }, 1000);
          });
        } else {
          addProduct(data).then(() => {
            ElMessage.success("提交成功");
            submitLoading.value = false;
            setTimeout(() => {
              router.push("/shop/product");
            }, 1000);
          });
        }
      } catch {
        submitLoading.value = false;
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<style lang="scss" scoped>
.card-item {
  margin-bottom: 10px;
}

.card-header {
  font-size: 16px;
  font-weight: 700;
}
</style>
